package cn.bud.msgbus.server.busdao;

import cn.bud.msgbus.server.bean.Subscriber;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.ResolvableType;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * BusDao
 *
 * @author hxj
 * @version 1.0
 * @description
 * @date 2024-07-17 15:35
 */
@Slf4j
@Component
public class BusDao {

    public ApplicationContext applicationContext;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void editSubscriber(Subscriber subscriber) {
        Map<String,SubscriberMapper> mapperMap = applicationContext.getBeansOfType(SubscriberMapper.class);
        if (MapUtils.isEmpty(mapperMap)) {
            log.warn("订阅者信息持久化异常，未找到对应的subscriberMapper，需要持久化的信息: {}",subscriber);
            return;
        }
        SubscriberMapper mapper = findMapper(mapperMap, subscriber.getClass());
        if (mapper == null) {
            log.warn("订阅者信息持久化异常，未找到对应的subscriberMapper，需要持久化的信息: {}", subscriber);
            return;
        }
        mapper.editSubscriber(subscriber);
    }

    private SubscriberMapper findMapper(Map<String,SubscriberMapper> mapperMap, Class<?> clazz) {
        for (Map.Entry<String, SubscriberMapper> entry : mapperMap.entrySet()) {
            ResolvableType forInstance = ResolvableType.forInstance(entry.getValue());
            for (ResolvableType anInterface : forInstance.getInterfaces()) {
                for (ResolvableType generic : anInterface.getGenerics()) {
                    if (clazz.equals(generic.resolve())) {
                        return entry.getValue();
                    }
                }
            }
        }
        return null;
    }

    public List<Subscriber> listSubscriber() {
        Map<String,SubscriberMapper> mapperMap = applicationContext.getBeansOfType(SubscriberMapper.class);
        if (MapUtils.isEmpty(mapperMap)) {
            return new ArrayList<>();
        }
        List<Subscriber> list = new ArrayList<>();
        for (Map.Entry<String, SubscriberMapper> entry : mapperMap.entrySet()) {
            list.addAll(entry.getValue().listSubscriber());
        }
        return list;
    }

//    public static void main(String[] args) {
//        HttpSubscriber httpSubscriber = new HttpSubscriber();
//        httpSubscriber.addTopic("wowow", null, null);
//        httpSubscriber.setUrl("thhttt");
//        System.out.println(httpSubscriber);
//    }
}
